//
//  TextFieldUI.swift
//  uiKit-demo
//
//  Created by 陈澎 on 2024/12/23.
//
import UIKit
import Foundation
class MyTextFieldUI:UIViewController, UITextFieldDelegate {
    // 输入框即将进入编辑状态时被调用
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        print("修改", textField)
        return true
    }
    // 输入框已经开始编辑时被调用
    func textFieldDidBeginEditing(_ textField: UITextField) {
        print("开始编辑")
    }
    // 输入框已经结束编辑时被调用
    func textFieldDidEndEditing(_ textField: UITextField) {
        print("编辑结束")
    }
    // 文本发生变化时被调用
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // 输入文字已经等于11位了
        if ((textField.text?.count)! >= 11) {
            print("输入文字不能多余11位")
            return false
        }
        if string.first == nil {
            return true
        }
        if string.first != nil && (string.first)! >= "0" && (string.first)! <= "9" {
            return true
        }
       
        print("只能输入0到9的数字")
        return false
    }
    // 输入框中清除按钮时被调用
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        print("清除文本")
        return true
    }
    // 键盘上的retrun按钮时调用
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        print("回车")
        //离开编辑ss111
        textField.resignFirstResponder()
        return true
    }
    func render(_ self: AnyObject, target: Any) {
        // 左视图
        let leftImageView = UIImageView(image: UIImage(named: "happyImg"))
        leftImageView.frame = CGRect(x: 0, y: 860, width: 30, height: 30)
        
        // 右视图
        let rightImageView = UIImageView(image: UIImage(named: "cryImg"))
        rightImageView.frame = CGRect(x: 0, y: 860, width: 30, height: 30)
        
        
        let textField = UITextField(frame: CGRect(x: 20, y: 860, width: 300, height: 30))
        textField.leftView = leftImageView
        textField.rightView = rightImageView
        // 设置UITextField空间的左右视图显示模式: never-从不显示 whileEditing-编辑状态时显示 unlessEditing:不处于编辑状态下显示 aways:总是显示
        textField.leftViewMode = UITextField.ViewMode.always
//        textField.rightViewMode = UITextField.ViewMode.always
        
        textField.clearButtonMode = UITextField.ViewMode.always
        // 边框
        textField.borderStyle = UITextField.BorderStyle.roundedRect
        // 红色文字
        textField.textColor = UIColor.red
        // 文字对齐方式
        textField.textAlignment = NSTextAlignment.left
        textField.placeholder = "请输入姓名"
        if let validDelegate = target as? UITextFieldDelegate {
            textField.delegate = validDelegate
        }
        self.addSubview(textField)
    }
}
